﻿using System;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.Web.Routing;
using log4net;
using Machinery.Cogs;
using NHibernate;
using NHibernate.Linq;
using Ninject;
using Ninject.Web.Mvc;

namespace Machinery
{
    public abstract class MachineryHttpApplication : NinjectHttpApplication, IPart
    {
        #region Machinery Shorthand
        public T Get<T>() { return Kernel.Get<T>(); }
        public ISession Database { get { return Kernel.Get<ISession>(); } }
        public INHibernateQueryable<T> DatabaseTable<T>() { return Get<ISession>().Linq<T>(); }
        #endregion

        protected override IKernel CreateKernel()
        {
            return new MachineryKernel();
        }

        public override void Init()
        {
            base.Init();
            log4net.Config.XmlConfigurator.Configure();
        }

        protected void Application_Error(Object sender, EventArgs e)
        {
            var exception = HttpContext.Current.Server.GetLastError();
            if (exception is HttpUnhandledException && exception.InnerException != null)
                exception = exception.InnerException;

            
            Get<ILogCog>().Log("UnhandledExceptions", LoggingLevel.Error, "Unhandled exception occured.", exception);
        }




    }
}